<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/5/30
 * Time: 9:41
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Message extends Base
{
    /**
     * 消息首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            //推送范围
            if(isset($params['m_range']) && $params['m_range'] != ''){
                $where['m_range'] =$params['m_range'] ;
            }
            //推送方式
            if(isset($params['m_way']) && $params['m_way'] != ''){
                $where['m_way'] =$params['m_way'] ;
            }
            //推送类型
            if(isset($params['m_type']) && $params['m_type'] != ''){
                $where['m_type'] =$params['m_type'] ;
            }
            //推送状态
            if(isset($params['m_status']) && $params['m_status'] != ''){
                $where['m_status'] =$params['m_status'] ;
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('message')
                ->join('up_notice', 'n_id = m_article_id', 'left')
                ->join('up_goods', 'good_id = m_goods_id', 'left')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('message')
                ->join('up_notice', 'n_id = m_article_id', 'left')
                ->join('up_goods', 'good_id = m_goods_id', 'left')
                ->field('m_id, m_range, m_way, m_datetime, m_time, m_type, m_status, m_updatetime, 
                good_name, n_title, m_title')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('m_datetime desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 发布消息
     * @return mixed|\think\response\Json
     */
    public function messageAdd(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if($params['m_way'] == 2 && $params['m_time'] == ''){
                return json(['code' => 100, 'msg' => '请选择发送时间']);
            }
            if($params['m_time'] != '' && strtotime($params['m_time']) <= time()){
                return json(['code' => 100, 'msg' => '发送时间不可早于当前时间']);
            }
            if($params['m_range'] == 2 && $params['school_id'] == ''){
                return json(['code' => 100, 'msg' => '请选择学校']);
            }
            if($params['m_range'] == 3 && $params['user_id'] == ''){
                return json(['code' => 100, 'msg' => '请选择用户']);
            }
            if($params['m_type'] == 1 && $params['m_goods_id'] == ''){
                return json(['code' => 100, 'msg' => '请选择商品']);
            }
            if($params['m_type'] == 2 && $params['m_article_id'] == ''){
                return json(['code' => 100, 'msg' => '请选择文章']);
            }
            $time = date('Y-m-d H:i:s');
            $data = [
                'm_title' => trim($params['m_title'], ' '),//标题
                'm_range' => $params['m_range'],//推送范围  1 全部  2 学校  3 个人
                'm_way' => $params['m_way'],//推送方式  1 即时推送  2 定时推送
                'm_datetime' => $time,//创建时间
                'm_type' => $params['m_type'],//推送类型  1 商品  2 文章
                'm_updatetime' => $time,//编辑时间
                'm_read' => ',0,',//已读
                'm_del' => ',0,'//已删
            ];
            //如果推送范围是全部，则存-1
            if($params['m_range'] == 1){
                $data['m_user'] = -1;
            }elseif($params['m_range'] == 2){
                //如果app需要消息列表，则使用注释部分
//                $user_id = Db::table('up_u_user')
//                    ->where('user_status', 1)
//                    ->where('user_school', 'IN', $params['school_id'])
//                    ->column('user_id');
//                $data['m_user'] = ',' . implode(',', $user_id) . ',';
                $data['m_user'] = $params['school_id'];
            }else{
                //如果app需要消息列表，则使用注释部分
//                $data['m_user'] = ',' . $params['user_id'] . ',';
                $data['m_user'] = $params['user_id'];
            }
            //如果推送方式为即时推送，则推送时间为当前时间，定时推送，则为选择的时间
            if($params['m_way'] == 1){
                $data['m_time'] = date('Y-m-d H');
                $data['m_status'] = 2;
            }else{
                $data['m_time'] = date('Y-m-d H', strtotime($params['m_time']));
                $data['m_status'] = 1;
            }
            $article_type = '';//文章类型
            //如果推送类型选择的是商品，则m_goods_id存商品ID,文章，则m_article_id存文章ID
            if($params['m_type'] == 1){
                $data['m_goods_id'] = $params['m_goods_id'];
                $send_id = $params['m_goods_id'];//用于推送
            }else{
                $data['m_article_id'] = $params['m_article_id'];
                $send_id = $params['m_article_id'];//用于推送
                //文章类型
                $article_type = Db::table('up_notice')->where('n_id', $send_id)->value('n_type');
            }
            $res = Db::table('up_message')->insert($data);
            if($res){
                //推送即时
                if($params['m_way'] == 1){
                    $type = 1;
                    if($params['m_range'] == 1){
//                        $user_ids = Db::table('up_u_user')
//                            ->where('user_status', 1)
//                            ->column('user_id');
                        $type = 2;
                        $user_ids = '';
                    }elseif($params['m_range'] == 2){
                        $user_ids = Db::table('up_u_user')
                            ->where('user_status', 1)
                            ->where('user_school', 'IN', $params['school_id'])
                            ->column('user_id');
                    }else{
                        $user_ids = explode(',', $params['user_id']);
                    }
                    $list = [];//需要推送的用户数组
                    if($user_ids){
                        foreach($user_ids as $k => $v){
                            $val = (string)$v;
                            array_push($list, $val);
                        }
                    }
                    try{
                        $this->Jpush($type, $list, $params['m_title'], ['send_type' => 2,'type' => $params['m_type'], 'send_id' => $send_id, 'n_type' => $article_type]);
                    }catch(\Exception $e){
                    }
                }
                
                return json(['code' => 200, 'msg' => '发布成功']);
            }else{
                return json(['code' => 100, 'msg' => '发布失败']);
            }
        }
        //所有商品
        $goods = Db::table('up_goods')
            ->field('good_id, good_name')
            ->where('good_status', 1)
            ->order('good_create_time desc')
            ->select();
        //所有文章
        $notice = Db::table('up_notice')
            ->field('n_id, n_title')
            ->where('n_status', 1)
            ->where('n_del', 1)
            ->order('n_time desc')
            ->select();
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->where('school_status', 1)
            ->where('school_del', 1)
            ->select();
        //所有用户
        $user = Db::table('up_u_user')
            ->field('user_id, user_username')
            ->where('user_status', 1)
            ->select();
        $this->assign([
            'goods' => $goods,
            'notice' => $notice,
            'school' => $school,
            'user' => $user
        ]);
        return $this->fetch('message/messageadd');
    }
    
    /**
     * 消息详情
     * @return mixed
     */
    public function messageDetail(){
        $m_id = input('m_id');
        $info = Db::name('message')
            ->join('up_goods', 'good_id = m_goods_id', 'left')
            ->join('up_notice', 'n_id = m_article_id', 'left')
            ->where('m_id', $m_id)
            ->field('good_name, n_title, m_title, m_range, m_user, m_way, m_datetime, m_time, m_type, 
            m_status')
            ->find();
        //推送范围
        if($info['m_range'] == 1){
            $info['username'] = '全部';
        }elseif($info['m_range'] == 2){
            $school_name = Db::name('school')->where('school_id', 'IN', $info['m_user'])->column('school_name');
            $info['username'] = implode(',', $school_name);
        }else{
            $user_name = Db::name('u_user')->where('user_id', 'IN', $info['m_user'])->column('user_username');
            $info['username'] = implode(',', $user_name);
        }
        $this->assign([
            'info' => $info
        ]);
        return $this->fetch('message/messagedetail');
    }
    
    /**
     * 删除消息
     * @return \think\response\Json
     */
    public function messageDel(){
        $m_id = input('id');
        $res = Db::table('up_message')->delete($m_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
}